package com.alibaba.cloud.application.query;

import com.alibaba.cloud.application.banktransfer.BankTransferCompletedEvent;
import com.alibaba.cloud.application.banktransfer.BankTransferCreatedEvent;
import com.alibaba.cloud.application.banktransfer.BankTransferFailedEvent;
import com.alibaba.cloud.domain.entity.BankTransfer;
import com.alibaba.cloud.infrastructure.repository.BankTransferRepository;
import org.axonframework.eventhandling.EventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BankTransferEventListener {

    private BankTransferRepository repository;

    @Autowired
    public BankTransferEventListener(BankTransferRepository repository) {
        this.repository = repository;
    }

    @EventHandler
    public void on(BankTransferCreatedEvent event) {
        repository.save(new BankTransfer(event.getBankTransferId(),
                event.getSourceBankAccountId(),
                event.getDestinationBankAccountId(),
                event.getAmount()));
    }

    @EventHandler
    public void on(BankTransferFailedEvent event) {
        BankTransfer bankTransferEntry = repository.findOneByAxonBankTransferId(event.getBankTransferId());
        bankTransferEntry.setStatus(BankTransfer.Status.FAILED);
        repository.save(bankTransferEntry);
    }

    @EventHandler
    public void on(BankTransferCompletedEvent event) {
        BankTransfer bankTransferEntry = repository.findOneByAxonBankTransferId(event.getBankTransferId());
        bankTransferEntry.setStatus(BankTransfer.Status.COMPLETED);
        repository.save(bankTransferEntry);
    }


}
